import WeCropper from '../we-cropper/we-cropper.js'
const app=getApp()
var util = require('../../utils/util.js');
//文件引用
// var CusBase64 = require('../../utils/base64.js');
//函数调用
const device = wx.getSystemInfoSync()
const width = device.windowWidth
const height = device.windowHeight
Page({
  data: {
    cropperOpt: {
      id: 'cropper',
      width: width,
      height: height,
      // pixelRatio: device.pixelRatio,
      scale: 2.5,
      zoom: 8,
      cut: {
        x: (width - 200) / 2,
        y: (height - 200) / 2,
        width: 200,
        height: 200
      }
    }
  },
  onLoad(option) {
    const { cropperOpt } = this.data
    if (option.src) {
      cropperOpt.src = option.src
      this.mycropper = new WeCropper(cropperOpt)
        .on('ready', (ctx) => {
          console.log(`wecropper is ready for work!`)
        })
        .on('beforeImageLoad', (ctx) => {
          console.log(`before picture loaded, i can do something`)
          console.log(`current canvas context:`, ctx)
          wx.showToast({
            title: '上传中',
            icon: 'loading',
            duration: 2000
          })
        })
        .on('imageLoad', (ctx) => {
          console.log(`picture loaded`)
          console.log(`current canvas context:`, ctx)
          wx.hideToast()
        })
        .on('beforeDraw', (ctx, instance) => {
          console.log(`before canvas draw,i can do something`)
          console.log(`current canvas context:`, ctx)
        })
        .updateCanvas()
    }
  },
  touchStart(e) {
    this.mycropper.touchStart(e)
  },
  touchMove(e) {
    this.mycropper.touchMove(e)
  },
  touchEnd(e) {
    this.mycropper.touchEnd(e)
  },
  //这个是保存上传裁剪后的图片的方法
  getCropperImage() {
    var that = this
    this.mycropper.getCropperImage((avatar) => {
      console.log(avatar)
      if (avatar) {
        // that.uploadImage(avatar, function (res) { })
        const tempFilePath = avatar;
        console.log(avatar)
        var imageType = "png";
        wx.getImageInfo({
          src: tempFilePath,
          success(res) {
            imageType = res.type;
          }
        })
        const imageName = tempFilePath.split("/");
        // console.log(imageName)
        console.log(imageName[imageName.length-1]);
        var baseCode = "";
        var myDate = new Date();
        var timestamp = new Date().getTime();
        // 图片转base64
        wx.getFileSystemManager().readFile({
          filePath: tempFilePath, //选择图片返回的相对路径
          encoding: 'base64', //编码格式
          success: res => { //成功的回调
            // console.log('data:image/' + imageType + ';base64,' + res.data)
            baseCode = res.data;
          }
        })
        var param = {
          "base64": 'data:image/' + imageType + ';base64,' + baseCode,
          "filename": imageName[imageName.length - 1],
        }
        var params = JSON.stringify(param);
        wx.request({
          url: 'https://papi.zcyun.cn/v1/user/avatar',
          data: {
            "base64": 'data:image/' + imageType + ';base64,' + baseCode,
            "filename": imageName[imageName.length - 1],
          },
          method: "PUT",
          header: {
            'content-type': 'application/json', // 默认值
            'openId': app.globalData.openId,
            'ts': timestamp,
            'sign': util.sha1("PUT" + '/v1/user/avatar' + params + timestamp + app.globalData.openKey)
          },
          success: function (res) {
            console.log(res.data);
            if (res.data.code == 0) {
              that.setData({
                imgSrc: tempFilePath,
              })
              // 获取到裁剪后的图片
              wx.redirectTo({
                url: '../me/pages/usersinfo/usersinfo'
              })
            }
          }
        })




      } else {
        console.log('获取图片失败，请稍后重试')
      }
    })
  },
  // 图片上传至服务器
   uploadImage:function(filePath, cb) {   //个人封装的简单的上传单张图片上传的方法
    wx.uploadFile({
      url: '',
      filePath: filePath,
      name: 'file',
      header: {
        "Content-Type": "multipart/form-data"
      },
      formData: {
        token: app.globalData.token,
        userName: "",
        portrait: filePath
      },
      success: function (res) {
        // 获取到裁剪后的图片
        console.log('上传图片成功')
        console.log(res);
        wx.showToast({
          title: '上传成功',
        })
        cb(res);
      },
      fail: function (res) {
        console.log('上传图片失败!')
        console.log(res)
        wx.showToast({
          title: '上传失败',
        })
      },
    })
   },
  // 重新选择
  uploadTap() {
    const self = this
    wx.chooseImage({
      count: 1, // 默认9
      sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
      sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
      success(res) {
        const src = res.tempFilePaths[0]
        // 获取裁剪图片资源后，给data添加src属性及其值
        self.mycropper.pushOrign(src)
      }
    })
  },
  // 取消
  cancelTap(){
    // 关闭当前页面，返回上一页面或多级页面
    wx.navigateBack({
      delta:1
    })
  }
})